<?php
App::uses('AppController', 'Controller');
/**
 * Courses Controller
 *
 * @property Course $Course
 * @property PaginatorComponent $Paginator
 */

App::import('Controller', 'CoursesCodes');
App::import('Controller', 'Users');
App::import('Controller', 'Professors');
//App::import('Controller', 'Sections');
App::import('Controller', 'Scheduleoptions');

class CoursesController extends AppController {

	
/**
 * Components
 *
 * @var array
 */
	public $components = array('Session','Paginator', 'Excel');
	public $helpers = array('Html', 'Form');


	var $Codes;
	var $Users;
	var $Professors;
	//var $Sections;
	var $Scheduleoptions;

/**
 * index method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function index($processId = null){ 
		$hayCursos = $this->Course->Section->find(
			'count', array(
				'conditions' => array(
					'Section.preinscription_process_id' => $processId
				)
			)
		);

		$this->set('processId', $processId);
	}

	public function verCursos() {
		$this->Course->recursive = 0;
		$this->set('courses', $this->Paginator->paginate());
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Course->exists($id)) {
			throw new NotFoundException(__('Invalid course'));
		}
		$options = array('conditions' => array('Course.' . $this->Course->primaryKey => $id));
		$this->set('course', $this->Course->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add($processId) {
		if ($this->request->is('post')) {
			$this->Course->create();
			if($this->Course->save($this->request->data)){ //Validamos si es que se puede guardar los datos recibidos
				$this->Session->setFlash('Cursos agregado');
				$this->redirect(array('controller' => 'Sections' ,'action' => 'index', $processId));				
			}
			$codigos = $this->Course->CoursesCode->find('list');
		}
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->Course->exists($id)) {
			throw new NotFoundException(__('Invalid course'));
		}
		$this->Course->id = $id;
		if($this->request->is('get')){
			//se llenan los datos para que los inputs se llenen en la vista edit
			$this->request->data = $this->Course->read();  
		}else{ //Peticion de tipo no GET
			if($this->Course->save($this->request->data)){
				$this->Session->setFlash('Curso '. $this->request->data['Course']['CoursesCode'].' guardado por edit!'); //Si es que se guardo se envia mensaje de exito
				$this->redirect(array('action'=>'ver_cursos')); //redireccionamos
			}else
				$this->Session->setFlash('No se pudo guardar en edit!');
		}
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Course->id = $id;
		if (!$this->Course->exists()) {
			throw new NotFoundException(__('Invalid course'));
		}
		if($this->request->is('get')){
			throw new MethodNotAllowedException();
		}else{ //sino ha sido mandado por POST
			if($this->Course->delete($id)){
				$this->Session->setFlash('Curso eliminado');
				$this->redirect(array('action'=>'ver_cursos'));
			}
		}
	}

	public function requisitos($id = null){
		$this->Course->id = $id;
		if($this->request->is('get')){
			$this->set('reqCurso', $this->Course->read()); 
		}
	}

	function beforeFilter() {
		$this->Codes =& new CoursesCodesController; /*Loads the class*/
		$this->Codes->constructClasses(); /*Loads the model associations, components, etc. of the Pages controller*/
		$this->Users =& new UsersController;
		$this->Users->constructClasses();
		$this->Professors =& new ProfessorsController;
		$this->Professors->constructClasses();
		//$this->Sections =& new SectionsController;
		//$this->Sections->constructClasses();
		$this->Scheduleoptions =& new ScheduleoptionsController;
		$this->Scheduleoptions->constructClasses();
	}




	// Funcion que carga el archivo excel con los cursos a un proceso en particular
	// Funcion que carga el archivo excel con los cursos a un proceso en particular
	public function upload(){
		if($this->request->is('post')){
			$inputFileName = $this->request->data['Course']['url']['name'];			
			$processId = $this->request->data['Course']['processId'];
			if($inputFileName != ''){
				$excel['data']['name'] = $inputFileName;
				$excel['data']['type'] = $this->request->data['Course']['url']['type'];
				$excel['data']['tmp_name'] = $this->request->data['Course']['url']['tmp_name'];
				$excel['data']['error'] = $this->request->data['Course']['url']['error'];
				$excel['data']['size'] = $this->request->data['Course']['url']['size'];
		         
				//Ir a Component > ExcelComponent para mayor informacion de 'validacion'
				if($msg=$this->Excel->validacion($excel)){
					$this->Session->setFlash($msg);
					$this->redirect(array('action'=>'index'));
				}				
				
				require_once '../Vendor/Excel/PHPExcel.php';
				require_once '../Vendor/Excel/PHPExcel/Reader/Excel2007.php';
				
				//Se carga el archivo
				$objReader = new PHPExcel_Reader_Excel2007();
				$objPHPExcel = $objReader->load($excel["data"]["tmp_name"]);
				$objPHPExcel->setActiveSheetIndex(0); //Seleccionamos la primera hoja del excel

				//Ir a Component > ExcelComponent para mayor informacion de 'formato'
				if($msg = $this->Excel->formato($excel, $objPHPExcel)){
					$this->Session->setFlash($msg);
					$this->redirect(array('action'=>'index'));
				}

				$i = 2; //primera fila leible del excel

				$course_i = 1;
				$seccion_i = 1;
				$codigo_i = 1;

		    	$max_row = $objPHPExcel->getActiveSheet()->getHighestRow();

				//Manejamos informacion para ser guardada
				$id = 0;

		    	while(true){
		    		$nombre = $objPHPExcel->getActiveSheet()->getCell('F'.$i)->getValue();

		    		if($nombre == '')
		    			break;

		    		//Cursos (info completa)
		    		$curso['Course']['name'] = $objPHPExcel->getActiveSheet()->getCell('F'.$i)->getValue();
		    		$curso['Course']['mandatory'] = ($objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue()=='obligatorio')?true:false;
		    		$curso['Course']['ud'] = $objPHPExcel->getActiveSheet()->getCell('D'.$i)->getValue();		    		
		    		$curso['Course']['requisite'] = $objPHPExcel->getActiveSheet()->getCell('J'.$i)->getValue();


		    		//Seccion 
		    		$seccion['Section']['room'] = ($objPHPExcel->getActiveSheet()->getCell('K'.$i)->getValue()=='SI')?true:false;
	    			$seccion['Section']['exam'] = ($objPHPExcel->getActiveSheet()->getCell('L'.$i)->getValue()=='SI')?true:false;
	    			$seccion['Section']['teacher_evaluation'] = ($objPHPExcel->getActiveSheet()->getCell('M'.$i)->getValue()=='SI')?true:false;
	    			$seccion['Section']['coordinator'] = $objPHPExcel->getActiveSheet()->getCell('N'.$i)->getValue();
	    			$seccion['Section']['observation'] = $objPHPExcel->getActiveSheet()->getCell('O'.$i)->getValue();
	    			$seccion['Section']['vacancy'] = $objPHPExcel->getActiveSheet()->getCell('E'.$i)->getValue();
		    		$seccion['Section']['preinscription_process_id'] = $processId;

		    		//capturo codigo de cursos
    				$codigoCompleto = $objPHPExcel->getActiveSheet()->getCell('A'.$i)->getValue();

    				//vemos si tiene codigo antiguo
    				$code_old[$i]['CoursesCode']['code']= trim($objPHPExcel->getActiveSheet()->getCell('B'.$i)->getValue());
    				
		    		//Scheduleoptions / Horarios en oferta
		    		$horarios = explode(',', trim($objPHPExcel->getActiveSheet()->getCell('H'.$i)->getValue()));
		    		$auxiliar = $objPHPExcel->getActiveSheet()->getCell('I'.$i)->getValue();

		    		//Profesor(es)
		    		$profesores = explode('/', trim($objPHPExcel->getActiveSheet()->getCell('G'.$i)->getValue()));

		    		//Separo en codigo y seccion
		    		$splitCodigo = explode('-',$codigoCompleto); 


		    		if(sizeof($splitCodigo) == 2){
		    			$codigo['CoursesCode']['code'] = $splitCodigo[0];
		    			$seccion['Section']['section_number'] = intval($splitCodigo[1]);
		    		}
		    		else{
		    			$codigo['CoursesCode']['code'] = $codigoCompleto;
		    			$seccion['Section']['section_number'] = 1;
		    		}

		    		

		    		//Consultamos si existe ya el codigo
		    		$existe[$i] = $this->Codes->existe($codigo['CoursesCode']['code']);
		    		// Guardamos el curso
		    		if(sizeof($existe[$i]) == 0){ //si curso no existe  			
		    			$this->Course->create();
		    			$this->Course->save($curso);

		    			$codigo['CoursesCode']['course_id'] = $this->Course->id;
		    			$this->Course->CoursesCode->create();		    			
		    			$this->Course->CoursesCode->save($codigo);

		    			//Si tiene codigo antiguo se guarda para almacenar mas tarde
		    			//de almacenarse altiro se sobreescriben filas de los cursos :( 
		    			if($code_old[$i]['CoursesCode']['code'] != ''){	    				
		    				$code_old[$i]['CoursesCode']['course_id'] = $this->Course->id;    				  					
			    		}

			    		//guardamos seccion			    		
			    		$seccion['Section']['course_id'] = $this->Course->id;
			    		$this->Course->Section->create();
			    		$this->Course->Section->save($seccion);


			    		//guardamos los profes
			    		$profesor['Professor']['section_id'] = intval($this->Course->Section->id);
			    		foreach($profesores as $profe){			    			
			    			$profesor['Professor']['user_id'] = $this->__buscarIdProfesor(trim($profe));
			    			$this->Professors->addExcel($profesor);
			    		}

			    		//guardamos scheduleoption
			    		$schedule['Scheduleoption']['section_id'] = intval($this->Course->Section->id);
			    		foreach($horarios as $horario){
			    			$schedule['Scheduleoption']['schedule'] = ($auxiliar!= '')?trim($horario).';'.trim($auxiliar):trim($horario);
			    			$this->Scheduleoptions->addExcel($schedule);
			    		}




		    		}else{ // Curso ya existe
		    			$this->Course->id = $existe[$i][0]['CoursesCode']['course_id'];
		    			$this->Course->save($curso);

		    			//seccion ya existe -> La modificamos
		    			if($seccionAModificar = $this->__seccionExiste($codigoCompleto, $processId)){
		    				$seccionAModificar = $seccionAModificar[0]['Section'];

		    				//guardamos seccion
			    			$seccion['Section']['course_id'] = $seccionAModificar['course_id'];
			    			$this->Course->Section->id = $seccionAModificar['id'];
			    			$this->Course->Section->save($seccion);
			    			//$this->Sections->addExcel($seccion);
			    			
			    			//Guardamos los profes
			    			$profesor['Professor']['section_id'] = intval($seccion['Section']['course_id']);
			    			$p = $this->__buscarProfesor($profesor['Professor']['section_id']);
			    			//Borramos los profesores
				    		foreach($p as $profe){
				    			$this->Professors->deleteExcel($profe['Professor']['id']);
				    		}
				    		//los creamos nuevamente
				    		foreach($profesores as $profe){			    			
				    			$profesor['Professor']['user_id'] = $this->__buscarIdProfesor(trim($profe));
				    			$this->Course->Section->Professor->create();
				    			$this->Course->Section->Professor->save($profesor);
				    		}

		    			}else{ //seccion no existe -> La creamos
			    			//guardamos seccion
			    			$seccion['Section']['course_id'] = $this->Course->id;
			    			$this->Course->Section->create();
			    			$this->Course->Section->save($seccion);
			    			//$this->Sections->addExcel($seccion);
			    			
			    			//Guardamos los profes
			    			$profesor['Professor']['section_id'] = intval($this->Course->Section->id);
				    		foreach($profesores as $profe){			    			
				    			$profesor['Professor']['user_id'] = $this->__buscarIdProfesor(trim($profe));
				    			$this->Professors->addExcel($profesor);
				    		}

				    		//guardamos scheduleoption
				    		$schedule['Scheduleoption']['section_id'] = intval($this->Course->Section->id);
				    		foreach($horarios as $horario){
				    			$schedule['Scheduleoption']['schedule'] = ($auxiliar!= '')?trim($horario).';'.trim($auxiliar):trim($horario);
				    			$this->Scheduleoptions->addExcel($schedule);
				    		}
				    	}

		    		}
		    		$i++;

		    	}

		    	//$this->Codes->addExcel($code_old);

		    	$this->Session->setFlash('Cursos agregados');
				$this->redirect(array('controller' =>'Sections' ,'action' => 'index', $processId));


		    }
		}
	}


	

	

	public function __seccionExiste($codigoCompleto, $procesoId){
		$codigo = explode('-', $codigoCompleto);
		if(sizeof($codigo) == 2){
			$codigoSinSeccion = $codigo[0];
			$seccion = $codigo[1];
		}else{ //Excel no trae seccion (seccion 1)		
			$codigoSinSeccion = $codigoCompleto;	
			$seccion = 1;		
		}
		$id_curso = $this->Codes->existe($codigoSinSeccion);
		return $existeSeccion = $this->Course->Section->find('all', array(
				'conditions' => array(
					'course_id' => $id_curso[0]['CoursesCode']['course_id'],
					'section_number' => $seccion,
					'preinscription_process_id' => $procesoId)));
	}

	
	public function __buscarIdProfesor($name){
		return $this->Users->buscarIdProfesor($name);		

	}

	public function __buscarProfesor($seccion_id){
		return $this->Professors->buscarProfesor($seccion_id);
	}
	

}
?>
